package com.zj.musicTools.function

import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import android.util.Log
import com.zj.musicTools.function.AppPath.Companion.appPath

/**
 * 数据库类
 *
 * 用途：用于方便对数据库数据操作
 *
 * 默认表名：config
 *
 * */
class SQLwriter(filename:String){
    private val debug=true
    private val tableName=filename
    private val sqlEditor: SQLiteDatabase = SQLiteDatabase.openOrCreateDatabase(appPath.getSetPath()+"/${tableName}.db3",null)
    init {
        val result=sqlEditor.execSQL("""create table if not exists ${tableName}(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL,value TEXT NOT NULL)""")//建表
        if(debug)
            Log.i("SQLwriter()", "create,$result"+"\n path:${appPath.getSetPath()+"/${tableName}.db3"}")
    }
    /**
     * 增加值
    * */
    private fun insert(name:String,value:String){
        var result:Long=0
        val content= ContentValues().apply {
            put("name",name)
            put("value",value)
        }
        try {
            result = sqlEditor.insert(tableName, null, content)
        }catch (e:Exception){
            Log.e("SQLwriter()",e.toString())
        }
//        sqlEditor.execSQL("insert into config values(?,?)",arrayOf(name,value))
        Log.i("SQLwriter()", "insert,${result}")
    }
    /**
     * 读取值
     * */
    private fun select(name:String):String?{
        var value :String? =null
        try {
            val result = sqlEditor.rawQuery("select * from config where name=?", arrayOf(name))
            if(result.count>0) {
                result?.use {
                    // 获取列索引
                    val nameIndex = it.getColumnIndex("name")
                    val valueIndex = it.getColumnIndex("value")
                    it.moveToNext()
                    value = it.getString(valueIndex)

                }
            }
            Log.i("SQLwriter()", "select,count:${result.count},value:${value.toString()}")
        }catch (e:Exception){
            Log.e("SQLwriter()",e.toString())
        }
        return value
    }
    /**
     * 修改值
     * */
    private fun update(name:String,value:String){
        var result=0
        val content= ContentValues().apply {
            put("value",value)
        }
        try {
            result = sqlEditor.update(tableName, content, "name=?", arrayOf(name))
        }catch (e:Exception){
            Log.e("SQLwriter()",e.toString())
        }
        Log.i("SQLwriter()", "update,$result")
    }
    /**
     * 删除项
    * */
    fun delete(name:String){
        var result=0
        try {
            result = sqlEditor.delete(tableName,"name=?", arrayOf(name))
        }catch (e:Exception){
            Log.e("SQLwriter()",e.toString())
        }
        Log.i("SQLwriter()", "delete,$result")
    }
    /**
     * 删除表格
    * */
    fun delTable(){
        sqlEditor.execSQL("drop table if exists $tableName")
    }
    fun set(name:String,value:String){
        if(select(name).isNullOrEmpty())
            insert(name,value)
        else
            update(name,value)
    }
    /**
     * 若失败，返回null
     * */
    fun get(name: String):String?{
        return select(name)
    }
    companion object{
        var configData = SQLwriter("config")

    }


}

/**
 *
 *  * 加入数据库，用于保存设置信息
 * https://blog.csdn.net/lanrenxiaowen/article/details/116484597
 * https://www.likecs.com/show-204149335.html#sc=1296
 *
 *
 * https://www.dandelioncloud.cn/article/details/1572594010609119234
 *https://blog.csdn.net/weixin_43977327/article/details/109776832
 *https://juejin.cn/post/7176272753211736119
 * */
